* required datasets: invitalia, OpenCoesione, bankdebt

clear all
set maxvar 100000 





use $data/OpenCoesione.dta, clear
gen date2=date(string(oc_data_pagament,"%8.0f"),"YMD")
format date2 %d
gen year=year(date2)
gen month=month(date2)

gen ym=ym(year,month)

collapse(sum) pagamenti , by(PROTOCOLLO ym data_fine)
 
 merge m:1 PROTOCOLLO using $data/invitalia.dta,  keep(3) nogen

gen uname = upper(RAGIONESOCIALE)
gen nome3=substr(uname,1,3)
destring PIVA, gen(codfisc_mef)
tostring codfisc_mef, format(%016.0f) replace



gen rata2=fondo_perduto/2
rename check_agg rata_agg
replace rata_agg=. if rata_agg<=0
gen rata_agg2=rata_agg/2
//gen quota6=QUOTAAGEVOLAZIONIINCONTOCAPI/6
egen thresholdrata=rowmin(rata2 rata_agg2 )




gen ratadummy=(pagamenti>=thresholdrata & pagamenti<.)
bys PROTOCOLLO: egen totrate=total(ratadummy)


sort  PROTOCOLLO ym

/**** sanity check ****
egen idcheck=group(codfisc)
egen idcheck2=group(codfisc nome3)
distinct idcheck* // ok
drop idcheck*
*******************/

//br codfisc_mef  ym pagamenti thresholdrata  ratadummy totrate QUOTAAGEVOLAZIONIINCONTOCAPI if totrate>=3
keep if ratadummy==1
bys PROTOCOLLO  (ym): gen totrimb=sum(pagament) 
gen share=totrimb/QUOTAAGEVOLAZIONIINCONTOCAPI
bys PROTOCOLLO  (ym): gen ordrimb=_n

distinct PROTOCOLLO if totrate==3  // 82 firms received 3 reimbursements, 3250 2 reimbursements, 3754 1 reimbursement
drop if totrate==3


/***********************************
drop  if ordrimb==2 & totrate==3
***********************************
drop totrate ordrimb
bys PROTOCOLLO: egen totrate=total(ratadummy)
bys PROTOCOLLO (ym): gen ordrimb=_n
************************************/


gen d_last=(share>.70 & share<.) 
tab  totrat d_last


/*** sanity check ****/
bys codfisc: egen checklast=total(d_last)
tab checklast



drop if checklast==2 | checklast==0   
//replace d_last=0   if ordrimb==2 & d_last==1 & totrate==3
drop checklast



g year_acc=year(DATAACC)
g month_acc=month(DATAACC)
//g codfisc=PIVA
//bys codfisc: g n=_n 
//keep if n==1
//drop n

g ym_accRSUD=ym(year_acc, month_acc)





//gen d_nolast=(d_last==0)   
keep pagamenti codfisc_mef ym* d_* ordrimb totrate FinBancario ym_accRSUD
rename pagamenti reimbursement
save $temp/dummyevents.dta , replace
keep codfisc_mef
duplicates drop
save $temp/codfisc_mef_dummyevents.dta, replace


**** other merges

use $data/bankdebt.dta, clear

//gen codfisc=codfisc_mef
merge 1:1 codfisc_mef ym using $data/uninps_RAS.dta,  nogen 
merge m:1 codfisc_mef using $data/infoc_panel_rich.dta, keep(3) nogen
merge m:1 codfisc_mef using $temp/codfisc_mef_dummyevents.dta, keep(3) nogen
merge 1:1 codfisc_mef ym using $temp/dummyevents.dta, keep(1 3) nogen

replace dip=0 if dip==.
replace bankdebt=0 if bankdebt==.
foreach x in ym_birth ym_death med_monte FinBancario {
bysort codfisc_mef (`x'): replace `x' = `x'[1] if missing(`x') 
}






sort codfisc ym




egen id=group(codfisc_mef)

keep if ym>=ym_birth
save $data/event_study_dataset.dta, replace 



